package com.snail.config;


import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.snail.utils.Subtitle;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class SrtGenerator {
    public String generateSRT(List<Subtitle> subtitles) {
        if (subtitles == null || subtitles.isEmpty()) return "";

        StringBuilder srtBuilder = new StringBuilder();

        for (int i = 0; i < subtitles.size(); i++) {
            Subtitle subtitle = subtitles.get(i);
            srtBuilder.append(i + 1).append("\n");
            srtBuilder.append(formatTime(subtitle.getStartTimeMillis()))
                    .append(" --> ")
                    .append(formatTime(subtitle.getEndTimeMillis()))
                    .append("\n");
            JSONObject jsonObject = JSONUtil.parseObj(subtitle.getText());
            String pureText = jsonObject.getStr("text");
            srtBuilder.append(pureText).append("\n");

        }

        return srtBuilder.toString();
    }

    private String formatTime(long milliseconds) {
        int hours = (int) (milliseconds / 3600000);
        int minutes = (int) ((milliseconds % 3600000) / 60000);
        int seconds = (int) ((milliseconds % 60000) / 1000);
        int millis = (int) (milliseconds % 1000);

        return String.format("%02d:%02d:%02d,%03d", hours, minutes, seconds, millis);
    }
}